#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import subprocess

def check_python():
    """检查Python是否安装"""
    try:
        result = subprocess.run([sys.executable, "--version"], 
                              capture_output=True, text=True, timeout=10)
        print(f"Python版本: {result.stdout.strip()}")
        return True
    except Exception as e:
        print(f"错误: 未找到Python，请先安装Python 3.7或更高版本: {e}")
        return False

def init_database():
    """初始化数据库"""
    try:
        print("正在初始化数据库...")
        # 添加项目根目录到Python路径
        project_root = os.path.dirname(os.path.abspath(__file__))
        backend_dir = os.path.join(project_root, "backend")
        sys.path.append(project_root)
        sys.path.append(backend_dir)
        
        # 导入并初始化数据库
        from backend.database.database import init_database
        init_database()
        print("数据库初始化完成")
        return True
    except Exception as e:
        print(f"警告: 数据库初始化失败: {e}")
        return False

def start_backend():
    """启动后端服务器"""
    try:
        print("正在启动后端服务器...")
        print("后端服务器正在运行在 http://localhost:8000")
        print("按 Ctrl+C 停止服务器")
        print("")
        
        # 进入backend目录启动服务器
        project_root = os.path.dirname(os.path.abspath(__file__))
        backend_dir = os.path.join(project_root, "backend")
        os.chdir(backend_dir)
        
        # 启动FastAPI服务器
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "main:app", 
            "--host", "0.0.0.0",
            "--port", "8000",
            "--reload"
        ])
        
    except KeyboardInterrupt:
        print("\n后端服务器已停止")
    except Exception as e:
        print(f"启动后端服务器时出错: {e}")

def main():
    """主函数"""
    print("网络云运维日报故障处理上报系统 - 后端服务")
    print("=" * 40)
    print("")
    
    # 检查Python环境
    if not check_python():
        input("按回车键退出...")
        return
    
    # 初始化数据库
    if not init_database():
        input("数据库初始化失败，按回车键退出...")
        return
    
    # 启动后端服务
    print("准备启动后端服务...")
    start_backend()

if __name__ == "__main__":
    main()